const recursion = (targetArr, bool, parentName, parentId) => {
  let arr1 = [];
  let arr2 = [];
  targetArr?.forEach(t => {
    if (!bool) {
      arr2.push({ ...t, parentName, parentId });
      if (t.listPeople && t.listPeople?.length > 0) {
        arr1.push(...t.listPeople);
      }
    }
    if (t.childList && t.childList?.length > 0) {
      recursion(t.childList, false, parentName, parentId, arr1, arr2);
    }
  });
  return { people: arr1, group: arr2 };
};

const unique = arr => {
  let newArr = [];
  arr.forEach(function (item) {
    if (newArr.findIndex(t => t.userId === item.userId) === -1) {
      newArr.push(item);
    }
  });
  return newArr;
};

const getAllPeopleAndGroup = arr => {
  let peopleList = [];
  let groupList = [];
  arr.forEach(t => {
    if (t.listPeople) {
      peopleList.push(...t.listPeople);
    }
    let { group, people } = recursion(t.childList, t.itSecondaryMenu, t.tabName, t.tabId);
    peopleList.push(...people);
    groupList.push(...group);
  });
  peopleList = unique(peopleList);
  return { people: peopleList, group: groupList };
};

export default getAllPeopleAndGroup;
